<script lang="ts" setup>
import { reactive, ref, computed } from "vue"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { createScoreRuleApi, updateScoreRuleApi } from "@/api/calculator"

interface Emits {
  (e: "success"): void
}

const emit = defineEmits<Emits>()

const visible = ref(false)
const currentData = ref<any | null>(null)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  rule_name: "",
  interval_start: 0,
  interval_end: undefined as number | undefined,
  unit: undefined as number | undefined,
  unit_add: 0,
  calculation_type: "",
  priority: 1,
  status: 1
})

const formRules: FormRules = reactive({
  rule_name: [{ required: true, trigger: "blur", message: "请输入规则名称" }],
  interval_start: [{ required: true, trigger: "blur", message: "请输入区间开始值" }],
  unit_add: [{ required: true, trigger: "blur", message: "请输入每单位加分数" }]
})

// 根据单位金额是否填写自动判断计算类型
const calculationType = computed(() => {
  return formData.unit && formData.unit > 0 ? "ratio" : "fixed"
})

const isEdit = ref(false)

const handleSubmit = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      const submitData = {
        rule_name: formData.rule_name,
        interval_start: formData.interval_start,
        interval_end: formData.interval_end,
        unit: formData.unit,
        unit_add: formData.unit_add,
        calculation_type: calculationType.value,
        priority: formData.priority,
        status: formData.status
      }

      const apiCall = isEdit.value
        ? updateScoreRuleApi({
            rule_id: currentData.value?.rule_id,
            ...submitData
          })
        : createScoreRuleApi(submitData)

      apiCall
        .then(() => {
          ElMessage.success(isEdit.value ? "修改成功" : "新增成功")
          emit("success")
          handleClose()
        })
        .catch(() => {
          ElMessage.error(isEdit.value ? "修改失败" : "新增失败")
        })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}

const resetForm = () => {
  formData.rule_name = ""
  formData.interval_start = 0
  formData.interval_end = undefined
  formData.unit = undefined
  formData.unit_add = 0
  formData.calculation_type = ""
  formData.priority = 1
  formData.status = 1
  formRef.value?.resetFields()
}

const handleClose = () => {
  visible.value = false
  resetForm()
}

// 打开对话框 - 新增模式
const openAdd = () => {
  isEdit.value = false
  currentData.value = null
  resetForm()
  visible.value = true
}

// 打开对话框 - 编辑模式
const openEdit = (data: any) => {
  isEdit.value = true
  currentData.value = data
  formData.rule_name = data.rule_name || ""
  formData.interval_start = data.interval_start || 0
  formData.interval_end = data.interval_end === null ? undefined : data.interval_end
  formData.unit = data.unit === null ? undefined : data.unit
  formData.unit_add = data.unit_add || 0
  formData.calculation_type = data.calculation_type || ""
  formData.priority = data.priority || 1
  formData.status = data.status || 1
  visible.value = true
}

// 暴露方法给父组件调用
defineExpose({
  openAdd,
  openEdit,
  resetForm,
  handleSubmit
})
</script>

<template>
  <el-dialog v-model="visible" :title="isEdit ? '修改加分规则' : '新增加分规则'" @close="handleClose" width="50%">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="left">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="rule_name" label="规则名称">
            <el-input v-model="formData.rule_name" placeholder="请输入规则名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="计算类型">
            <el-tag :type="calculationType === 'ratio' ? 'success' : 'info'">
              {{ calculationType === "ratio" ? "按单位比例加分" : "固定值" }}
            </el-tag>
            <span class="calculation-type-hint">
              {{
                calculationType === "ratio" ? "（已填写单位金额，将按比例计算）" : "（未填写单位金额，将按固定值计算）"
              }}
            </span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="interval_start" label="金额区间起始">
            <el-input-number v-model="formData.interval_start" :min="0" :precision="2" placeholder="请输入起始金额" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="interval_end" label="金额区间结束">
            <el-input-number
              v-model="formData.interval_end"
              :min="0"
              :precision="2"
              placeholder="请输入结束金额（可选）"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="unit" label="单位金额">
            <el-input-number v-model="formData.unit" :min="0" :precision="2" placeholder="请输入单位金额（可选）" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="unit_add" label="每单位加">
            <el-input-number v-model="formData.unit_add" :min="0" :precision="2" placeholder="请输入每单位加" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="priority" label="优先级">
            <el-input-number v-model="formData.priority" :min="1" placeholder="请输入优先级" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="status" label="状态">
            <el-select v-model="formData.status" placeholder="请选择状态">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.calculation-type-hint {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}
</style>
